/**************************************************************
 * @file     bsp_key.c
 * @brief    实现按键驱动队列发送消息
 * @author   Ruilist
 * @date     2025-07-25
 * @version  V1.0.0
 * @copyright Copyright (c) 2025
 *
 * @note     1 tab = 4 space
 *
 * @par 日志:
 * - V1.0.0 2025-07-25 Ruilist
 *   实现按键驱动队列发送消息
 **************************************************************/

#include "bsp_key.h"

osThreadId_t key_TaskHandle;

const osThreadAttr_t key_Task_attributes = {
    .name       = "key_Task",
    .stack_size = 128 * 4,
    .priority   = (osPriority_t)osPriorityHigh,
};

QueueHandle_t key_queue;

/**
 * @brief   按键状态轮询
 *
 * @param   *key_value    用作按键状态传参
 *
 * @return  返回值类型 key_status_t
 *
 */

key_status_t key_scan( key_press_status_t *key_value )
{
    uint32_t           counter          = 0;
    key_press_status_t key_status_value = KEY_NOT_PRESSED;

    while ( counter < 1000 )
    {
        if ( GPIO_PIN_RESET == HAL_GPIO_ReadPin( Key_GPIO_Port, Key_Pin ) )
        {
            key_status_value = KEY_PRESSED;
            *key_value       = key_status_value;
            return KEY_OK;
        }
        counter++;
    }
    *key_value = key_status_value;

    return KEY_ERRORTIMEOUT;
}

/**
 * @brief   按键任务
 *
 * @param   *argument    任务默认参数
 *
 * @return  空
 *
 */
void key_task_func( void *argument )
{
    printf( "start key_task_func\r\n" );

    key_status_t       ket_ret     = KEY_OK;
    key_press_status_t key_statues = KEY_NOT_PRESSED;
    key_queue                      = xQueueCreate( 10, sizeof( uint32_t ) );
    uint32_t counter_tick          = 0;
    if ( NULL == key_queue )
    {
        printf( "key_queue created failed \r\n" );
    }
    else
    {
        printf( "key_queue created successfully \r\n" );
    }
    for ( ;; )
    {
        counter_tick++;
        ket_ret = key_scan( &key_statues );

        if ( KEY_OK == ket_ret )
        {
            if ( KEY_PRESSED == key_statues )
            {
                printf( "Key_Pressed\r\n" );
                if ( pdTRUE == xQueueSendToFront( key_queue, &counter_tick, 0 ) )
                {
                    printf( "send successfully\r\n" );
                }
            }
        }
        if ( KEY_OK != ket_ret )
        {
            printf( "Key_not_Pressed\r\n" );
        }
        osDelay( 100 );
    }
}
